<?php

namespace app\logic\model\order;

use app\admin\model\user\UserModel;
use app\api\model\order\OrderEntityDetailApiModel;
use app\logic\model\LogicModel;
use app\logic\model\user\UserLogicModel;
use think\model\concern\SoftDelete;

class OrderEntityLogicModel extends LogicModel
{
    use SoftDelete;
    protected $name='order_entity';
    protected $delete_time = 'delete_time';
    public function getList(\think\Request $request, array $where, string $field='*', $page = 1, $limit=15,$order='id desc')
    {
        $query=$this->where($where)
            ->where(function ($q) use ($request){
                if(check_request($request,'status')){
                    $q->whereLike("status",$request['status']);
                }
                if(check_request($request,'user')){
                    $q->whereIn("buyer_id",UserLogicModel::getIdsByName($request['user']));
                }
                if(check_request($request,'start_time')&&check_request($request,'end_time')){
                    $q->whereBetween("create_time",[$request['start_time'],$request['end_time']." 23:59:59"]);
                }elseif (check_request($request,'start_time')){
                    $q->where("create_time",">=",$request['start_time']);
                }elseif (check_request($request,'end_time')){
                    $q->where("create_time","<=",$request['end_time']." 23:59:59");
                }
            });
        $list = $query->field($field)->order($order)->page($page,$limit)->select();
        $count = $query->count();
        if($count>0){
            $list = $list->toArray();
            $buyer_id = array_column($list,'buyer_id');
            $users = UserModel::getInfosByIds($buyer_id);
            foreach ($list as &$val){
                $val['detail'] = OrderEntityDetailApiModel::getByOrderId($val['id']);
                $val['buyer'] = $users[$val['buyer_id']]??[];
            }
        }
        return [$list,$count];
    }

}